package com.safewind.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.safewind.dao.AddressDao;
import com.safewind.dao.AddressGroupDao;
import com.safewind.model.AddressGroup;
import com.safewind.service.IAddressGroupService;
import com.safewind.util.StringUtil;

@Service("addressGroupService")
public class AddressGroupServiceImpl implements IAddressGroupService {
	@Resource
	private AddressGroupDao addressGroupDao;

	@Resource
	private AddressDao addressDao;

	@Override
	public void addGroup(AddressGroup group) {
		addressGroupDao.insert(group);
	}

	@Override
	public void addGroupWithIdAndName(Map<String, String> map, String userId) {
		for (String key : map.keySet()) {
			if (addressGroupDao.selectByPrimaryKey(map.get(key)) != null) {
				continue;
			}
			AddressGroup group = new AddressGroup();
			group.setAddTime(new Date());
			group.setGroupName(key);
			group.setGroupOrder((byte) 0);
			group.setPkId(map.get(key));
			group.setRemark(null);
			group.setUpdateTime(new Date());
			group.setUserId(userId);
			addGroup(group);
		}
	}

	@Override
	public AddressGroup getAddressGroupById(String addressGroupId) {
		return addressGroupDao.selectByPrimaryKey(addressGroupId);
	}

	@Override
	public AddressGroup getAddressGroupDefault(String userId) {
		return addressGroupDao.selectDefault(userId);
	}

	@Override
	public List<AddressGroup> getAllGroup(String userId) {
		return addressGroupDao.getAllGroup(userId);
	}

	@Override
	public AddressGroup selectAddressGroupByName(String name, String userId) {
		List<AddressGroup> agList = addressGroupDao.selestAddressGroupByName(
				name, userId);
		if (agList != null && agList.size() != 0) {
			return agList.get(0);
		}
		return new AddressGroup();
	}

	@Override
	public void deleteAddressGroupByIds(String ids) {
		if (StringUtil.isBlank(ids)) {
			return;
		}
		String[] id = ids.split(",");
		for (String str : id) {
			addressDao.deleteAllByGroupId(str);
			addressGroupDao.deleteByPrimaryKey(str);
		}
	}

	@Override
	public void deleteAllByUserId(String userId) {
		addressDao.deleteAllByUserId(userId);
		addressGroupDao.deleteAllByUserId(userId);
	}

}
